package de.lmu.ifi.pst.uwejsf.framework;

import java.beans.PropertyDescriptor;

import javax.script.ScriptContext;
import javax.script.SimpleScriptContext;

import org.apache.commons.beanutils.PropertyUtils;

public class RootBeanScriptContext extends SimpleScriptContext {
	private Object rootBean;

	@Override
	public Object getAttribute(String name) {
		if (name.equalsIgnoreCase("self"))
			return rootBean;
		Object attr = super.getAttribute(name);
		if (attr == null) {
			if (rootBean == null)
				return null;
			try {
				attr = PropertyUtils.getProperty(rootBean, name);
			} catch (Exception e) {
				// don't handle this since the script engine will probably throw
				// an exception anyway
			}
		}

		return attr;
	}

	public RootBeanScriptContext(Object root) {
		super();
		this.rootBean = root;

	}

	@Override
	public int getAttributesScope(String name) {
		if (name.equalsIgnoreCase("self"))
			return ScriptContext.ENGINE_SCOPE;
		
		int scope = super.getAttributesScope(name);
		if (scope < 0) {
			if (rootBean == null)
				return -1;
			try {
				PropertyDescriptor pd = PropertyUtils.getPropertyDescriptor(
						rootBean, name);
				if (pd != null && pd.getReadMethod() != null)
					scope = ScriptContext.ENGINE_SCOPE;
			} catch (Exception e) {

			}
		}
		return scope;
	}

	public Object getRootBean() {
		return rootBean;
	}

	public void setRootBean(Object rootBean) {
		this.rootBean = rootBean;
	}

}
